package lagou.filter;

import io.jsonwebtoken.Claims;
import lagou.tool.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {


    //注册请求的次数
    @Value("${ip.times}")
    private Integer registerTimes;
    //注册请求的时间间隔：秒
    @Value("${ip.seconds}")
    private Integer registerSeconds;

    //key为IP，value为注册的次数
    private static Map<String, Integer> registerTimesMap = new HashMap<>();
    //key为IP，value为注册最近一次的时间
    private static Map<String, Long> registerSecondsMap = new HashMap<>();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断当前的请求是否为登录，如果是，直接放行
        if (request.getURI().getPath().contains("/user") ||
                request.getURI().getPath().contains("/email")
                ||  request.getURI().getPath().contains("/code/create")
               ) {
            //放行
            return chain.filter(exchange);
        }


//注册时验证
        if(request.getURI().getPath().contains("user/register")) {
            // 从request对象中获取客户端ip
            String clientIp = request.getRemoteAddress().getHostString();
            //判断注册次数
            if(registerTimesMap.containsKey(clientIp)) {
                Integer times = registerTimesMap.get(clientIp) + 1;

                if(times > registerTimes) {
                    response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
                    String data = "register fail!";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
                registerTimesMap.put(clientIp, times);
            }else {
                registerTimesMap.put(clientIp, 1);
            }

            //判断注册时间
            Long now = System.currentTimeMillis();
            if(registerSecondsMap.containsKey(clientIp)) {
                Long lastTime = registerSecondsMap.get(clientIp);

                if((now - lastTime) < registerSeconds * 1000) {
                    response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
                    String data = "register fail!";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
            registerSecondsMap.put(clientIp, now);
            return chain.filter(exchange);
        }



        //3.获取当前用户的请求头jwt信息
        HttpHeaders headers = request.getHeaders();
        String jwtToken = headers.getFirst("token");

        //4.判断当前令牌是否存在
        if (StringUtils.isEmpty(jwtToken)) {
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //5.如果令牌存在，调用用户微服务验证token
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            int result = AppJwtUtil.verifyToken(claims);
            if (result == 0 || result == -1) {
                //5.1 合法，则向header中重新设置userId
                Integer id = (Integer) claims.get("id");
                log.info("find userid:{} from uri:{}", id, request.getURI());
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", id + "");
                }).build();
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //想客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //6.放行
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
